﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;
using Microsoft.Office.Interop.Word;

namespace WordTDD
{
    public class TDDGeneration
    {
        Application     wordApp = null;
        Document        wordDoc = null;
        Bookmark        definitionBookmark;
        Bookmark        insertAtBookmark;
        Range           definitionRange;
        Range           insertAtRange;
        Range           currentRange;

        public TDDGeneration()
        {
            wordApp = new Application();
            wordApp.Visible = false;
        }

        public void showWordApp()
        {
            wordApp.Visible = true;
        }

        public void createNewDoc(string filePath)
        {
            wordDoc = wordApp.Documents.Open(filePath);
        }

        public void saveDoc(string filePath)
        {
            wordDoc.SaveAs(filePath, WdSaveFormat.wdFormatDocument);
        }

        public void copyBookmark(string bookmarkNameToCopy, string bookmarkNameInsertAt)
        {
            if (wordDoc == null)
            {
                throw new System.Exception("Documetn not open for edit [ieide1]");
            }

            currentRange = null;

            if (wordDoc.Bookmarks.Exists(bookmarkNameToCopy))
            {
                definitionBookmark = wordDoc.Bookmarks[bookmarkNameToCopy];

                if (wordDoc.Bookmarks.Exists(bookmarkNameInsertAt))
                {
                    insertAtBookmark = wordDoc.Bookmarks[bookmarkNameInsertAt];

                    definitionRange = definitionBookmark.Range;
                    insertAtRange = insertAtBookmark.Range;
                    definitionRange.Copy();
                    insertAtRange.Paste();

                    currentRange = insertAtRange;
                }
            }                    
        }

        public void replaceText(string textToFind, string textToReplace)
        {
            if (currentRange == null)
            {
                throw new System.Exception("Range is not selected [ieide2]");
            }
            else
            {
                File.WriteAllText(@"c:\temp\logTDD.txt", currentRange.ToString());
            }

            currentRange.Collapse(WdCollapseDirection.wdCollapseStart);
            currentRange.Find.Execute(textToFind, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, textToReplace);
        }
    }
}
